package cl.gob.minvu.catastro.util;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.jboss.logging.Logger;


/**
 * @author psep
 *
 */
public final class PasswordManager {
	
	private static String HASH_ALGORITHM = "SHA-512";
	private static final Logger logger = Logger.getLogger(PasswordManager.class);
	private static boolean configured = false;

	/**
	 * Setea el tipo de algoritmo a ser usado en la encriptacion
	 * 
	 * @param algoritmo
	 *            ("SHA", "SHA-512"..etc)
	 * 
	 */
	public static void setHashAlgorithm(String algoritmo) {
		if (!configured) {
			HASH_ALGORITHM = algoritmo;
			configured = true;
		}
	}

	/**
	 * Retorna el string encriptado
	 * 
	 * @param plaintext
	 * @return String encyptado
	 */
	public static String encrypt(String plaintext) {
		String respuesta = "";
		
		if (plaintext == null) {
			return null;
		}

		try {
			MessageDigest md = getMessageDigest();

			byte[] first = plaintext.getBytes("UTF-8");
			md.update(first);
			byte raw[] = md.digest();
			respuesta = toString(raw);
			
		} catch (UnsupportedEncodingException e) {
			logger.error(e, e);
		}
		return respuesta;
	}

	/**
	 * @param raw
	 * @return
	 */
	private static String toString(byte[] raw) {
		StringBuffer buffer = new StringBuffer();
		for (int i = 0; i < raw.length; i++) {
			int eachByte = (int) raw[i] & 0xFF;

			if (eachByte < 10) {
				buffer.append("00" + eachByte);
			} else if (eachByte < 100) {
				buffer.append("0" + eachByte);
			} else {
				buffer.append(eachByte);
			}

		}
		
		return buffer.toString();
	}

	/**
	 * @return
	 */
	private static MessageDigest getMessageDigest() {
		MessageDigest mg = null;
		
		try {
			mg = MessageDigest.getInstance(PasswordManager.HASH_ALGORITHM);
		} catch (NoSuchAlgorithmException e) {
			logger.error(e, e);
		}
		
		return mg;
	}

}